//
//  LoopView.swift
//  6-轮播图
//
//  Created by apple on 2017/8/18.
//  Copyright © 2017年 HEJJY. All rights reserved.
//

import UIKit

protocol LoopViewDelegate : class {
    
    func LoopViewDelegate(_ currentIndex : Int)
}

class LoopView: UIView {
    
    var imageArray : [String] = [String]()
    var timer : Timer?
    weak var delegate : LoopViewDelegate?
    
    fileprivate lazy var imageViews : [UIImageView] = [UIImageView]()
    
    init(frame: CGRect, imageArray : [String]) {
        super.init(frame: frame)
        
        
        self.imageArray = imageArray
        backgroundColor = UIColor.white
        
        addSubview(scrollView)
        scrollView.isPagingEnabled = true
        scrollView.contentSize = CGSize(width: self.width * CGFloat(imageArray.count + 2), height: self.height)
    
        // 添加第一张图片
        let firstImage = UIImageView()
        firstImage.isUserInteractionEnabled = true
        let firstName = imageArray.last
        if let firstName = firstName {
            firstImage.image = UIImage(named: firstName)
        }
        firstImage.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height)
        scrollView.addSubview(firstImage)

        
        for i in 0..<imageArray.count {
            
            let imageView = UIImageView()
            imageView.isUserInteractionEnabled = true
            
            imageView.tag = i
            
            let currentName : String = imageArray[i]
            imageView.image = UIImage(named: currentName)
            imageView.frame = CGRect(x: self.width * CGFloat(i + 1), y: 0, width: self.width, height: self.height)
            scrollView.addSubview(imageView)
            self.imageViews.append(imageView)
            
            let tap = UITapGestureRecognizer(target: self, action:#selector(tapGesture(_ :)))
            imageView.addGestureRecognizer(tap)
        }
        
        // 添加最后一张图片
        let lastImage = UIImageView()
        lastImage.isUserInteractionEnabled = true
        let lastName = imageArray.first
        if let lastName = lastName {
            lastImage.image = UIImage(named: lastName)
        }
        lastImage.frame = CGRect(x: self.width * CGFloat(imageArray.count + 1), y: 0, width: self.width, height: self.height)
        scrollView.addSubview(lastImage)
        
        // 添加指示
        addSubview(pageControl)
        
        // 默认滚动第一张
        scrollView.contentOffset = CGPoint(x: self.width, y: 0)
    
        // 添加定时器
        addTimer()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 懒加载
    fileprivate lazy var scrollView : UIScrollView = {
    
        let scroll = UIScrollView(frame: self.bounds)
        scroll.delegate = self
        scroll.backgroundColor = UIColor.white
        scroll.showsHorizontalScrollIndicator = false
        return scroll
    }()
    
    fileprivate lazy var pageControl : UIPageControl = {
    
        let page = UIPageControl(frame:CGRect(x: 0, y: self.height - 30, width: self.width, height: 30))
        page.numberOfPages = self.imageArray.count
        page.currentPageIndicatorTintColor = UIColor.orange
        page.currentPage = 0
        page.pageIndicatorTintColor = UIColor.white
        return page
    }()

    // 布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        
    }

}

// #MARK:自定义方法
extension LoopView {

    @objc func tapGesture(_ gesture : UIGestureRecognizer) {
        
        let index = gesture.view?.tag
        
        if let index = index {
            delegate?.LoopViewDelegate(index)
        }
    }
    
    func addTimer()  {
        
        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(scrollToNext), userInfo: nil, repeats: true)
    }
    
    func invalidTimer() {
        timer?.invalidate()
    }
    
    @objc func scrollToNext() {
        
        var page = pageControl.currentPage
        
        if page == self.imageArray.count {
            
            page = 0
        } else {
           page = page + 1
        }
        
        scrollView.setContentOffset(CGPoint(x: self.width * CGFloat(page + 1), y: 0), animated: true)
    
    }
    
}

// #MARK:scrollView代理方法
extension LoopView : UIScrollViewDelegate {
    
    // 开始拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        invalidTimer()
    }
    
    // 结束拖拽
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        addTimer()
    }
    
    // 正在拖拽
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        var page : Int = Int((scrollView.contentOffset.x + self.width * 0.5) / self.width)
        
        if page == (self.imageArray.count + 1) {
            page = 1
        } else if page == 0 {
            page = self.imageArray.count
        }
        
        pageControl.currentPage = page - 1
    }
    
    // 减速时会调用
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page : Int = Int((scrollView.contentOffset.x + self.width * 0.5) / self.width)
        
        if page == self.imageArray.count + 1 {
            scrollView.setContentOffset(CGPoint(x: self.width, y: 0), animated: false)
        } else if page == 0 {
            scrollView.setContentOffset(CGPoint(x: CGFloat(self.imageArray.count) * self.width, y: 0), animated: false)
        }
        
    }
    
    // 设置contentoffset时调用
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
        scrollViewDidEndDecelerating(scrollView)
    }
}
